package top.ajun.mall.product.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.ajun.common.constants.ProductConstant;
import top.ajun.common.utils.PageUtils;
import top.ajun.common.utils.Query;
import top.ajun.mall.product.dao.AttrAttrgroupRelationDao;
import top.ajun.mall.product.dao.AttrDao;
import top.ajun.mall.product.dao.AttrGroupDao;
import top.ajun.mall.product.dao.CategoryDao;
import top.ajun.mall.product.entity.AttrAttrgroupRelationEntity;
import top.ajun.mall.product.entity.AttrEntity;
import top.ajun.mall.product.entity.AttrGroupEntity;
import top.ajun.mall.product.entity.CategoryEntity;
import top.ajun.mall.product.service.AttrService;
import top.ajun.mall.product.service.CategoryService;
import top.ajun.mall.product.vo.AttrGroupRelationVo;
import top.ajun.mall.product.vo.AttrRespVo;
import top.ajun.mall.product.vo.AttrVo;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    private AttrAttrgroupRelationDao attrAttrgroupRelationDao;
    @Autowired
    private AttrGroupDao attrGroupDao;
    @Autowired
    private CategoryDao categoryDao;

    @Autowired
    private CategoryService categoryService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
            new Query<AttrEntity>().getPage(params),
            Wrappers.query()
        );
        return new PageUtils(page);
    }

    @Override
    public AttrRespVo getAttrInfo(Long attrId) {
        AttrRespVo attrRespVo = new AttrRespVo();
        AttrEntity attrEntity = this.getById(attrId);
        BeanUtils.copyProperties(attrEntity, attrRespVo);

        // 查询分组信息并设置，基本属性才需要设置关联关系
        if (attrEntity.getAttrType() == ProductConstant.ATTR_TYPE_BASE.getCode()) {
            AttrAttrgroupRelationEntity relationEntity = attrAttrgroupRelationDao.selectOne(
                Wrappers.<AttrAttrgroupRelationEntity>lambdaQuery()
                    .eq(AttrAttrgroupRelationEntity::getAttrId, attrEntity.getAttrId())
            );
            if (relationEntity != null) {
                attrRespVo.setAttrGroupId(relationEntity.getAttrGroupId());
                AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(relationEntity.getAttrGroupId());
                if (attrGroupEntity != null) {
                    attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }
        }

        // 查询分类信息并设置
        Long catelogId = attrEntity.getCatelogId();
        Long[] path = categoryService.findCatelogPath(catelogId);
        attrRespVo.setCatelogPath(path);
        CategoryEntity categoryEntity = categoryDao.selectById(catelogId);
        if (categoryEntity != null) {
            attrRespVo.setCatelogName(categoryEntity.getName());
        }
        return attrRespVo;
    }

    @Override
    public PageUtils queryAttrPage(Map<String, Object> params, Long catelogId, String type) {
        String key = (String) params.get("key");
        LambdaQueryWrapper<AttrEntity> wrapper =
            Wrappers.<AttrEntity>lambdaQuery()
                .eq(AttrEntity::getAttrType, "base".equalsIgnoreCase(type) ?
                    ProductConstant.ATTR_TYPE_BASE.getCode() :
                    ProductConstant.ATTR_TYPE_SALE.getCode());
        if (!StrUtil.isEmpty(key)) {
            wrapper.and(obj -> obj.eq(AttrEntity::getAttrId, key).or().like(AttrEntity::getAttrName, key));
        }
        if (catelogId != 0) {
            wrapper.eq(AttrEntity::getCatelogId, catelogId);
        }

        // 数据处理，避免连表查询
        IPage<AttrEntity> page = page(new Query<AttrEntity>().getPage(params), wrapper);
        PageUtils pageUtils = new PageUtils(page);
        List<AttrRespVo> attrRespVoList = page.getRecords().stream().map(attrEntity -> {
            AttrRespVo attrRespVo = new AttrRespVo();
            BeanUtils.copyProperties(attrEntity, attrRespVo);

            // 设置分组名称，仅规格参数需要设置分组信息
            if ("base".equalsIgnoreCase(type)) {
                AttrAttrgroupRelationEntity relationEntity = attrAttrgroupRelationDao.selectOne(
                    Wrappers.<AttrAttrgroupRelationEntity>lambdaQuery()
                        .eq(AttrAttrgroupRelationEntity::getAttrId, attrEntity.getAttrId())
                );
                if (relationEntity != null && relationEntity.getAttrGroupId() != null) {
                    AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(relationEntity.getAttrGroupId());
                    if (attrGroupEntity != null) {
                        attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
                    }
                }
            }

            // 设置分类名称
            CategoryEntity categoryEntity = categoryDao.selectById(attrEntity.getCatelogId());
            if (categoryEntity != null) {
                attrRespVo.setCatelogName(categoryEntity.getName());
            }
            return attrRespVo;
        }).collect(Collectors.toList());

        pageUtils.setList(attrRespVoList);
        return pageUtils;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveAttr(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);
        // 保存基本数据
        this.save(attrEntity);
        // 保存关联关系，基本属性才需要保存关联关系
        if (attr.getAttrType() == ProductConstant.ATTR_TYPE_BASE.getCode() && attr.getAttrGroupId() != null) {
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrGroupId(attr.getAttrGroupId());
            relationEntity.setAttrId(attrEntity.getAttrId());
            attrAttrgroupRelationDao.insert(relationEntity);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateAttr(AttrVo attr) {
        // 基本属性修改
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);
        this.updateById(attrEntity);

        if (attr.getAttrType() == ProductConstant.ATTR_TYPE_BASE.getCode()) {
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrGroupId(attr.getAttrGroupId());
            relationEntity.setAttrId(attr.getAttrId());

            Integer count = attrAttrgroupRelationDao.selectCount(
                Wrappers.<AttrAttrgroupRelationEntity>lambdaQuery()
                    .eq(AttrAttrgroupRelationEntity::getAttrId, attr.getAttrId())
            );
            if (count > 0) {
                // 修改分组关联
                attrAttrgroupRelationDao.update(
                    relationEntity,
                    Wrappers.<AttrAttrgroupRelationEntity>lambdaUpdate()
                        .eq(AttrAttrgroupRelationEntity::getAttrId, attr.getAttrId())
                );
            } else {
                // 新增分组关联
                attrAttrgroupRelationDao.insert(relationEntity);
            }
        }
    }

    @Override
    public List<AttrEntity> getRelatedAttr(Long attrgroupId) {
        // 在关联表中查到所有和 attrGroupId 关联的 attrId，在根据这些 attrId 查到需要的 Attr
        List<AttrAttrgroupRelationEntity> relationList = attrAttrgroupRelationDao.selectList(
            Wrappers.<AttrAttrgroupRelationEntity>lambdaQuery()
                .eq(AttrAttrgroupRelationEntity::getAttrGroupId, attrgroupId)
        );
        List<Long> attrIdList = relationList.stream()
            .map(AttrAttrgroupRelationEntity::getAttrId)
            .collect(Collectors.toList());
        return CollUtil.isEmpty(attrIdList) ? null : this.listByIds(attrIdList);
    }

    @Override
    public void deleteRelation(List<AttrGroupRelationVo> relationVos) {
        List<AttrAttrgroupRelationEntity> relations = relationVos.stream().map(item -> {
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            BeanUtils.copyProperties(item, relationEntity);
            return relationEntity;
        }).collect(Collectors.toList());
        attrAttrgroupRelationDao.deleteBatchRelations(relations);
    }

    @Override
    public PageUtils getNotRelatedAttr(Map<String, Object> params, Long attrgroupId) {
        // 当前分组只能关联自己所属分类中的所有属性
        AttrGroupEntity attrGroup = attrGroupDao.selectById(attrgroupId);
        // 当前分组所属分类的 ID
        Long catelogId = attrGroup.getCatelogId();

        // 当前分组只能关联其它分组未引用的属性
        // 找到当前分类下的其它分组
        List<AttrGroupEntity> attrGroupList = attrGroupDao.selectList(
            Wrappers.<AttrGroupEntity>lambdaQuery()
                .eq(AttrGroupEntity::getCatelogId, catelogId)
        );
        // 所有其它分组的 ID
        List<Long> attrGroupIdList = attrGroupList.stream()
            .map(AttrGroupEntity::getAttrGroupId)
            .collect(Collectors.toList());

        // 找到这些分组关联的属性
        List<AttrAttrgroupRelationEntity> relationList = attrAttrgroupRelationDao.selectList(
            Wrappers.<AttrAttrgroupRelationEntity>lambdaQuery()
                .in(AttrAttrgroupRelationEntity::getAttrGroupId, attrGroupIdList)
        );
        // 所有其它分组关联的所有属性 id
        List<Long> attrIdList = relationList.stream()
            .map(AttrAttrgroupRelationEntity::getAttrId)
            .collect(Collectors.toList());

        // 从当前分类的所有属性中移除这些属性
        LambdaQueryWrapper<AttrEntity> wrapper = Wrappers.<AttrEntity>lambdaQuery()
            .eq(AttrEntity::getCatelogId, catelogId)
            .eq(AttrEntity::getAttrType, ProductConstant.ATTR_TYPE_BASE.getCode());
        if (CollUtil.isNotEmpty(attrIdList)) {
            wrapper.notIn(AttrEntity::getAttrId, attrIdList);
        }
        String key = (String) params.get("key");
        if (StrUtil.isEmpty(key)) {
            wrapper.and(attr -> attr.eq(AttrEntity::getAttrId, key).or().like(AttrEntity::getAttrName, key));
        }
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), wrapper);
        return new PageUtils(page);
    }

}